$(function() {
    chapter.init();
})

var chapter = (function() {
    
    function novelContentHandler() {
        $('#saveChaptersubmit').click(function() {
            var novelId = $('#manga_id').val(),
                chapterId = $('#chapter_id').val(),
                chapterTitle = $('#chapterTitle').val(),
                status = $('#chapterStatus input:radio[name=status]:checked').val(),
                content = $('#novelContent').code();
            content = content.replace(/(<br>)+/g, '<br>');    
            chapter.saveChapterContent(novelId, chapterId, chapterTitle, status, content, function(resp) {
                if (resp.err != 0) {
                    $('#editor_err_msg').show().find('.alert').attr('class', 'alert alert-error noMargin').html(resp.msg);
                } else {
                    $('#editor_err_msg').show().find('.alert').attr('class', 'alert alert-success noMargin').html('Successfull.');
                }
            });
            return false;
        });
        
        $('#deleteChapterCtn').click(function() {
            showConfirm({
                title: 'Delete Chapter',
                msg: 'Are you sure want to delete this chapter?',
                onYes: function() {
                    $('#listImg ul').html('');
                    $.post('/novel/ajax_delete_chapter', {
                        novelId: $('#manga_id').val(),
                        chapterId: $('#chapter_id').val(),
                        slug: $('#manga_slug').val()
                    }, function(resp) {
                        if (resp.err != 0) {
                            $('#chapterErr').addClass('text-error').show().html('Remove chapter content false');
                        } else {
                            $('#chapterDetail').hide();
                        }
                    }, 'json')
                }
            });
            return false;
        });
    }

    function chapter_handler() {
        $('#inpAddChapter').keypress(function(evt) {
            evt.keyCode == 13 && $('#btnAddChapter').click();
        });

        $('#btnAddChapter').click(function() {
            var novelId = $('#manga_id').val(),
                num = $('#inpAddChapter').val();
            chapter.createNewChapter(novelId, num);
            return false;
        });

        $('#chapterList li a').live('click', function() {
            var a = $(this),
                chapter = $(this).attr('rel');
            $('#chapterList li a').removeClass('selected').find('.badge').removeClass('bOlive');
            a.addClass('selected').find('.badge').addClass('bOlive');
            $.ajax({
                type: "POST",
                url: '/novel/ajax_get_chapter_content',
                data: {chapterId: chapter, novelId: $('#manga_id').val()},
                dataType: 'json',
                beforeSend: function() {
                    $('#chapterDetail').show();
                    $('#chapterErr').attr('class', 'hide pull-right').hide().html('');
                    $('#chapter_id').val(chapter);
                    $('#updateChapterCtn').attr('rel', chapter);
                    $('#chapterDetail .wContent').hide();
                    $('#wEditor').html('<div id="novelContent"></div>');
                },
                success: function(resp) {
                    if (resp.err != 0) {
                        $('#chapterErr').addClass('text-error').show().html(resp.msg);
                        return false;
                    }
                    $('#chapterDetail .wContent').show();
                    $('#novelContent').summernote({
                        height: 350,
                        focus: true 
                    });
                    $('#chapterTitle').val(resp.data.title);
                    $('chapterStatus input:radio[value=' + resp.data.status + ']').attr('checked', 'checked');
                    if (resp.data.content) {
                        $('#novelContent').code(resp.data.content);
                    }
                    return false;
                }
            });
            return false;
        });
    }


    return {
        init: function() {
            chapter_handler();
            novelContentHandler();
        },
        
        createNewChapter: function(novelId, chapterId, callback) {
            if (!/^[0-9]{1,4}$/i.test(chapterId)) {
                $('#inpAddChapter').addClass('error');
                return;
            }
            var url = '/novel/ajax_add_new_chapter';
            $.ajax({
                type: "POST",
                url: url,
                data: {chapterId: chapterId, novelId: novelId},
                dataType: 'json',
                beforeSend: function() {
                    $('#inpAddChapter').removeClass('error');
                },
                success: function(resp) {
                    if (resp.err == 0 && !$('#chapterList li a[rel="' + chapterId + '"]').length) {
                        var html = '<li class="alert-info" style="display:none;">\
                                        <a rel="' + chapterId + '" href="#">\
                                            <span class="badge noShadow bSky">' + chapterId + '</span>\
                                        </a>\
                                    </li>';
                        html = $(html);
                        $('#inpAddChapter').val('');
                        $('#chapterList').append(html);
                        html.fadeIn(500);
                        setTimeout(function() {
                            html.removeClass('alert-info');
                        }, 5000);
                    }
                    $.isFunction(callback) && callback(resp);
                }
            });
        },
        
        saveChapterContent: function(novelId, chapterId, chapterTitle, status, content, callback) {
            $('#err_msg').hide().find('.alert').attr('class', 'alert alert-error noMargin');
            $.post('/novel/ajax_save_chapter_content', {
                novelId: novelId,
                chapterId: chapterId,
                title: chapterTitle,
                status: status,
                content: content
            }, function(resp) {
                $.isFunction(callback) && callback(resp);
            }, 'json');
        }
        
    };

})();

